package cntv.player.core;

import cntv.player.core.util.LogUtil;
import cntv.player.core.util.SprefUtils;
import com.cntv.cbox.player.core.CBoxP2PCore;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

/**
 * P2P初始化任务
 * 
 * @author zengliang
 * 
 */
public class P2PInitTask implements Runnable {
	private static final String TAG = "zl";
	private Context mContext;
	private Handler mHandler;
	private CBoxP2PCore mCBoxP2PCore;
	private int mInitDelayTime = 500;

	public P2PInitTask(Context context, Handler handler) {
		this.mContext = context;
		this.mHandler = handler;
		this.mCBoxP2PCore = CBoxP2PCore.getInstance();
	}

	/**
	 * 启动p2p插件，并加载升级模块
	 */
	private void start(Context context) {
		String path = "SD=" + CBoxFileUtil.getAppFilePath(context) + "&SYS=" + CBoxFileUtil.getDataPath() + context.getPackageName();
		LogUtil.i(TAG, "P2PInitTask start() path = " + path);
		mCBoxP2PCore.InstanceAutoStart(path);
	}

	/**
	 * 停止p2p插件,如果p2p插件启动失败，需要停止后，再重新启动插件，
	 */
	private void stop() {
		mCBoxP2PCore.InstanceAutoStop();
	}
	
	public void run() {
//		if (!SprefUtils.getInstance(mContext).getBoolean("p2pInitSuccess")) {
		if (!CBoxStaticParam.P2P_INIT_SUCCESS_STATE) {
			stop();
			start(mContext);
			CBoxStaticParam.P2P_INIT_SUCCESS_STATE = true;
//			SprefUtils.getInstance(mContext).putBoolean("p2pInitSuccess", true);
		}

		int runState = 0;
		mHandler.removeMessages(CBoxStaticParam.P2P_INIT);
		mHandler.removeMessages(CBoxStaticParam.P2P_INIT_SUCCESS);
		mHandler.removeMessages(CBoxStaticParam.P2P_INIT_FAIL);

		try {
			runState = Integer.parseInt(mCBoxP2PCore.InstanceGetStat());
		} catch (Exception e) {
			LogUtil.e(TAG,"P2PInitTask run() State:Failed runState Exception... ");
			Message msg = new Message();
			msg.what = CBoxStaticParam.P2P_INIT_FAIL;
			msg.obj = "-10";
			mHandler.sendEmptyMessage(CBoxStaticParam.P2P_INIT_FAIL);
		}
		if (runState == 5) {
			LogUtil.e(TAG, "P2PInitTask run() State:OK");
			mHandler.sendEmptyMessage(CBoxStaticParam.P2P_INIT_SUCCESS);
		} else {
			LogUtil.e(TAG, "P2PInitTask run() State =" + runState);
			Message msg = new Message();
			msg.obj = mCBoxP2PCore.InstanceGetStatStr();
			if (runState < 0) {
				LogUtil.e(TAG, "P2PInitTask run() State:Failed runState = " + runState);
				msg.what = CBoxStaticParam.P2P_INIT_FAIL;
				mHandler.sendMessage(msg);
			} else if (runState == 3) {
				msg.what = CBoxStaticParam.P2P_INIT_UPDATE;
				mHandler.sendMessageDelayed(msg, 50);
			} else {
				msg.what = CBoxStaticParam.P2P_INIT;
				mHandler.sendMessageDelayed(msg, mInitDelayTime);
			}
		}
	}
}
